package net.godcode.olivenotes.pages.blog.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import net.godcode.olivenotes.components.admin.ImageSetBuilder;
import net.godcode.olivenotes.entities.Post;
import net.godcode.olivenotes.entities.PostDAO;
import net.godcode.olivenotes.entities.Tag;
import net.godcode.olivenotes.entities.TagDAO;
import net.godcode.olivenotes.services.TagSplitter;

import org.apache.tapestry.annotations.Component;
import org.apache.tapestry.corelib.components.Form;
import org.apache.tapestry.corelib.components.Submit;
import org.apache.tapestry.ioc.annotations.Inject;
import org.apache.tapestry.ioc.annotations.Symbol;
import org.apache.tapestry.services.RequestGlobals;
import org.apache.tapestry.upload.services.UploadedFile;
import org.slf4j.Logger;

/**
 * PostCreate
 * 
 * @author Chris Lewis Dec 28, 2007 <chris@thegodcode.net>
 * @version $Id: CreatePost.java 30 2008-01-20 23:42:30Z burningodzilla $
 */
public class CreatePost {
	
	@Inject
	private TagSplitter tagSplitter;
	
	@Inject
	private TagDAO tagDao;
	
	@Inject
	private PostDAO postDao;
	
	@Inject
	private Logger log;
	
	@SuppressWarnings("unused")
	@Component(id = "postForm")
	private Form cPostForm;
	
	@SuppressWarnings("unused")
	@Component(id = "publish")
	private Submit sPublish;
	
	@SuppressWarnings("unused")
	@Component(id = "draft")
	private Submit sDraft;
	
	@SuppressWarnings("unused")
	@Component(id = "imgBuilder")
	private ImageSetBuilder imgBuilder;
	
	private String postTitle;
	
	private String postBody;
	
	private String postTags;
	
	private boolean postPublished;
	
	private static final Pattern postNamePattern = Pattern.compile("[^a-zA-Z0-9\\-\\_]");
	
	/**/
	
	@Inject
	private RequestGlobals request;
	
	@Inject @Symbol("blog.uploads.images-fixme")
	private String uploadPath;
	
	private static File targetDir;	
	
	void onPrepare() {
		//TODO nasty
		if(targetDir == null) {
			targetDir = new File(request.getHTTPServletRequest().getRealPath("/"), uploadPath);
		}
	}
	
	/**
	 * @return the postTitle
	 */
	public String getPostTitle() {
		return postTitle;
	}

	/**
	 * @param postTitle the postTitle to set
	 */
	public void setPostTitle(String postTitle) {
		this.postTitle = postTitle;
	}

	/**
	 * @return the postBody
	 */
	public String getPostBody() {
		return postBody;
	}

	/**
	 * @param postBody the postBody to set
	 */
	public void setPostBody(String postBody) {
		this.postBody = postBody;
	}
	
	void onSelectedFromPublish() {
		postPublished = true;
	}
	
	void onSelectedFromDraft() {
		postPublished = false;
	}
	
	void onSuccessFromPostForm() {
		
		if(imgBuilder.getUploadedImages().size() > 0) {
			moveFiles();
		}
		
		Post post = new Post();
		post.setPublished(postPublished);
		post.setTitle(getPostTitle());
		post.setBody(getPostBody()); //TODO validate + sanitize
		
		/*
		 * Here we produce a post name for this post. Post names are
		 * shortened and sanitized versions of the post title.
		 * TODO need max length
		 * TODO ensure uniqueness
		 */
		String title = post.getTitle().toLowerCase().replace(' ', '-');
		post.setName(postNamePattern.matcher(title).replaceAll(""));
		
		String rawTags = getPostTags();
		if(rawTags != null) {
			String[] sTags = tagSplitter.splitAsStrings(getPostTags());
			for(String tag : sTags) {
				//TODO TagSplitter should insulate this
				String tagName = tag.toLowerCase().replace(' ', '-');
				//TODO verify save
				Tag _tag = tagDao.save(new Tag(postNamePattern.matcher(tagName).replaceAll("")));
				post.getTags().add(_tag);
			}
		}
		
		postDao.save(post); //TODO verify save
	}

	/**
	 * @return the postTags
	 */
	public String getPostTags() {
		return postTags;
	}
	
	/**
	 * @param postTags the postTags to set
	 */
	public void setPostTags(String postTags) {
		this.postTags = postTags;
	}

	/**
	 * @return the postPublished
	 */
	public boolean getPostPublished() {
		return postPublished;
	}

	/**
	 * @param postPublished the postPublished to set
	 */
	public void setPostPublished(boolean postPublished) {
		this.postPublished = postPublished;
	}
	
	private void moveFiles() {
		if(! targetDir.exists()) {
			if(! targetDir.mkdirs()) {
				throw new RuntimeException("Failed to create the target directory!");
			}
		} else if(! targetDir.isDirectory()) {
			throw new RuntimeException("Target node exists but is not a directory!");
		} else if(! targetDir.canWrite()) {
			throw new RuntimeException("Target directory exists but is not writeable!");
		}
		
		for(UploadedFile uf : imgBuilder.getUploadedImages()) {
			File copied = new File(targetDir, uf.getFileName());
			uf.write(copied);
			log.error(" -- copied: " + copied.getAbsolutePath());
		}
	}
	
}
